package com.seeyon.apps.ebs.event;

import com.seeyon.apps.collaboration.event.CollaborationFinishEvent;
import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.event.EventTriggerMode;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.annotation.ListenEvent;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class SendFormToEmailEventListener {

    private static final Log log = LogFactory.getLog(SendFormToEmailEventListener.class);
    private FormApi4Cap4 cap4FormManager = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
    private ColManager colManager ;
    public ColManager getColManager() {
        return colManager;
    }

    public void setColManager(ColManager colManager) {
        this.colManager = colManager;
    }
    private OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
    private EnumManager enumManager = (EnumManager) AppContext.getBean("enumManagerNew");
    private static final String workInfoForm = AppContext.getSystemProperty("ebs.workInfoForm");
    private static final String sendEmailName = AppContext.getSystemProperty("ebs.sendEmailName");
    private static final String sendEmailPassword = AppContext.getSystemProperty("ebs.sendEmailPassword");


    @ListenEvent(event = CollaborationFinishEvent.class,mode = EventTriggerMode.afterCommit)
    public void onCollaborationFilsh(CollaborationFinishEvent event){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            ColSummary summary =colManager.getSummaryById(event.getSummaryId());
            Long formAppid = summary.getFormAppid();
            FormBean form = cap4FormManager.getForm(formAppid, false);
            String nowTableName = form.getMasterTableBean().getTableName();
            Long formRecordid = summary.getFormRecordid();
            FormBean workForm = cap4FormManager.getFormByFormCode(workInfoForm);
            String tableName = workForm.getMasterTableBean().getTableName();
            if (nowTableName.equals(tableName)){
                FormDataMasterBean masterData = cap4FormManager.getDataMasterBeanById(formRecordid, workForm, null);
                FormFieldBean wellNameBean = workForm.getFieldBeanByDisplay("井名");
                StringBuilder context = new StringBuilder("<html><body>");
                //作业申请人
                String workApplicantValue = "";
                FormFieldBean workApplicantBean = workForm.getFieldBeanByDisplay("申请人");
                Object workApplicantObject = masterData.getFieldValue(workApplicantBean.getName());
                if (workApplicantObject!=null){
                    long workApplicantId = Long.parseLong(String.valueOf(workApplicantObject));
                    V3xOrgMember member = orgManager.getMemberById(workApplicantId);
                    workApplicantValue = member.getName();
                }
                context.append("<b>" + "作业申请人:" + "</b>").append(workApplicantValue).append("<br>");
                //作业部门
                String workDeptValue = "";
                FormFieldBean workDeptBean = workForm.getFieldBeanByDisplay("作业部门");
                Object workDeptObject = masterData.getFieldValue(workDeptBean.getName());
                if (workDeptObject==null){
                    log.info("作业部门为空");
                }else {
                    CtpEnumItem workDeptItem = enumManager.getEnumItem(Long.parseLong(String.valueOf(workDeptObject)));
                    workDeptValue = workDeptItem.getShowvalue();
                }
                context.append("<b>" + "作业部门:" + "</b>").append(workDeptValue).append("<br>");
                FormFieldBean keyPointBean = workForm.getFieldBeanByDisplay("关键点提示");
                FormFieldBean noteBean = workForm.getFieldBeanByDisplay("备注");
                List<FormDataSubBean> subData = masterData.getSubData(keyPointBean.getOwnerTableName());
                String title = "";
                List<String> wellList = new ArrayList<>();
                if (subData!=null&& !subData.isEmpty()){
                    for (int i = 0; i < subData.size(); i++) {
                        FormDataSubBean formDataSubBean = subData.get(i);
                        //获取井名
                        Object wellNameValue = formDataSubBean.getFieldValue(wellNameBean.getName());
                        if (wellNameValue==null){
                            log.info("井名为空");
                        }else {
                            String wellValue = wellNameValue.toString();
                            wellList.add(wellValue);
                            context.append("<b>" + "井名").append(i + 1).append(":").append("</b>").append(wellValue).append("<br>");
                        }
                        //作业类型
                        String workTypeValue = "";
                        FormFieldBean workTypeBean = workForm.getFieldBeanByDisplay("作业类型");
                        Object workTypeObject = formDataSubBean.getFieldValue(workTypeBean.getName());
                        if (workTypeObject==null){
                            log.info("作业类型为空");
                        }else {
                            workTypeValue = workTypeObject.toString();
                            context.append("<b>" + "作业类型").append(i + 1).append(":").append("</b>").append(workTypeValue).append("<br>");
                        }
                        //作业内容
                        String workContentValue = "";
                        FormFieldBean workContentBean = workForm.getFieldBeanByDisplay("作业内容");
                        Object workContentObject = formDataSubBean.getFieldValue(workContentBean.getName());
                        if (workContentObject==null){
                            log.info("作业内容为空");
                        }else {
                            workContentValue = workContentObject.toString();
                            context.append("<b>" + "作业内容").append(i + 1).append(":").append("</b>").append(workContentValue).append("<br>");
                        }
                        //预计作业开始时间
                        String startTimeValue = "";
                        FormFieldBean startTimeBean = workForm.getFieldBeanByDisplay("起始时间");
                        Object startTimeObject = formDataSubBean.getFieldValue(startTimeBean.getName());
                        if (startTimeObject!=null){
                            startTimeValue = sdf.format(startTimeObject);
                            context.append("<b>" + "起始时间").append(i + 1).append(":").append("</b>").append(startTimeValue).append("<br>");
                        }
                        //预计作业结束时间
                        String endTimeValue = "";
                        FormFieldBean endTimeBean = workForm.getFieldBeanByDisplay("结束时间");
                        Object endTimeObject = formDataSubBean.getFieldValue(endTimeBean.getName());
                        if (endTimeObject!=null){
                            endTimeValue = sdf.format(endTimeObject);
                            context.append("<b>" + "结束时间").append(i + 1).append(":").append("</b>").append(endTimeValue).append("<br>");
                        }
                        Object keyPointObject = formDataSubBean.getFieldValue(keyPointBean.getName());
                        Object noteObject = formDataSubBean.getFieldValue(noteBean.getName());
                        if (keyPointObject!=null){
                            CtpEnumItem keyPointItem = enumManager.getEnumItem(Long.parseLong(String.valueOf(keyPointObject)));
                            String keyPointValue = keyPointItem.getShowvalue();
                            context.append("<b>" + "关键点提示").append(i + 1).append(":").append("</b>").append(keyPointValue).append("<br>");
                        }
                        FormFieldBean sameWellBean = workForm.getFieldBeanByDisplay("同井场井");
                        Object sameWellObject = formDataSubBean.getFieldValue(sameWellBean.getName());
                        if (sameWellObject!=null){
                            context.append("<b>" + "同井场井").append(i + 1).append(":").append("</b>").append(sameWellObject).append("<br>");
                        }
                        if (noteObject!=null){
                            context.append("<b>" + "备注").append(i + 1).append(":").append("</b>").append(noteObject).append("<br>");
                        }
                    }
                }
                //注
                String zhuValue = "";
                FormFieldBean zhuBean = workForm.getFieldBeanByDisplay("注");
                Object zhuObject = masterData.getFieldValue(zhuBean.getName());
                if (zhuObject!=null){
                    zhuValue = zhuObject.toString();
                    context.append("<b>"+"注:"+"</b>").append(zhuValue).append("<br>");
                }
                //作业审批人
                String workApproverValue = "";
                FormFieldBean workApproverBean = workForm.getFieldBeanByDisplay("作业审批人");
                Object workApproverObject = masterData.getFieldValue(workApproverBean.getName());
                if (workApproverObject!=null){
                    workApproverValue = String.valueOf(workApproverObject);
                    context.append("<b>" + "作业审批人:" + "</b>").append(workApproverValue).append("<br>");
                }
                context.append("</body></html>");
                log.info("context:"+context);
                FormFieldBean emailBean = workForm.getFieldBeanByDisplay("邮箱");
                //获取标题
                FormFieldBean titleBean = workForm.getFieldBeanByDisplay("标题");
                Object titleObject = masterData.getFieldValue(titleBean.getName());
                if (titleObject!=null){
                    title = StringUtils.join(wellList,",")+ titleObject;
                }
                List<FormDataSubBean> subDataList = masterData.getSubData(emailBean.getOwnerTableName());
                if (subDataList!=null&& !subDataList.isEmpty()){
                    for (FormDataSubBean subData1 : subDataList) {
                        Object emailObject = subData1.getFieldValue(emailBean.getName());
                        if (emailObject!=null){
                            sendFormToEmail(emailObject.toString(), title, context.toString());
                        }
                    }
                }
            }
        }catch (Exception e) {
            log.error("发送邮件失败",e);
        }
    }

    private void sendFormToEmail(String email,String title,String context) {
        //测试邮箱
            String to = email;//oa@ebspetroleum.com  shuaiqidedio@outlook.com
            String from = sendEmailName;
            String host = "smtp-mail.outlook.com";
            Properties properties = System.getProperties();
            properties.setProperty("mail.smtp.host",host);
            properties.setProperty("mail.smtp.auth","true");
            properties.setProperty("mail.smtp.port", "587");
            properties.setProperty("mail.smtp.starttls.enable","true");
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(sendEmailName,sendEmailPassword);
                }
            });
            try {
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
                message.setSubject(title);
                //message.setText(context);
                message.setContent(context,"text/html;charset=UTF-8");
                Transport.send(message);
            }catch (MessagingException e){
                log.error("发送邮件失败",e);
            }
    }
}
